{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding: utf-8\n",
    "# server\n",
    "\n",
    "import socket\n",
    "\n",
    "sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
    "sock.bind((\"localhost\", 8080))\n",
    "sock.listen(1) # 监听客户端连接\n",
    "while True:\n",
    "    conn, addr = sock.accept()  # 接收一个客户端连接\n",
    "    print conn.recv(1024) # 从接收缓冲读消息 recv buffer\n",
    "    conn.sendall(\"world\") # 将响应发送到发送缓冲 send buffer\n",
    "    conn.close() # 关闭连接\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 以上代码搬到 pycharm 上运行是成功的， server 一直运行，需要手动停止\n",
    "# client 运行， 会接收到 world 信息，同时 server端会收到 hello 信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "world\n"
     ]
    }
   ],
   "source": [
    "# coding: utf-8\n",
    "# client\n",
    "\n",
    "import socket\n",
    "\n",
    "sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
    "sock.connect((\"localhost\", 8080)) # 连接服务器\n",
    "sock.sendall(\"hello\")  # 将消息输出到发送缓冲 send buffer\n",
    "print sock.recv(1024)  # 从接收缓冲 recv buffer 中读响应\n",
    "sock.close() # 关闭套接字\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
